<template>
  <div class="comment-list">
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      :error="error"
      error-text="加载失败，请点击重试"
      @load="onLoad"
      :immediate-check="false"
    >
      <comment-item
        v-for="(item, index) in list"
        :comment="item"
        :key="index"
        @reply-click="$emit('reply-click', $event)"
      />
    </van-list>
  </div>
</template>

<script>
import { getComments } from '@/api/comment'
import CommentItem from './comment-item'

export default {
  name: 'CommentList',
  components: {
    CommentItem,
  },
  props: {
    source: {
      type: [Number, String, Object],
      required: true,
    },
    list: {
      type: Array,
      // vue中默认验证数组需要为函数
      default: () => [],
    },
    type: {
      type: String,
      // 自定义 prop 数据验证
      validator(value) {
        return ['a', 'c'].includes(value)
      },
      default: 'a',
    },
  },
  data() {
    return {
      // list: [],
      loading: false,
      finished: false,
      // 获取下一页数据的标记
      offset: null,
      // 获取每页的评论个数
      limit: 10,
      error: false,
    }
  },
  computed: {},
  watch: {},
  created() {
    // 当我们利用created调用onload函数时，他不会自动初始化loading
    // 所以我们要手动开启初试话loading
    this.loading = true
    this.onLoad()
  },
  mounted() {},
  methods: {
    async onLoad() {
      try {
        // 请求获取数据
        const { data } = await getComments({
          type: this.type,
          source: this.source.toString(),
          offset: this.offset,
          limit: this.limit,
        })
        // 将数据添加到列表中
        const { results } = data.data
        this.list.push(...results)
        // console.log(data.data)
        this.$emit('onload-success', data.data)
        // 将loading设置为false
        this.loading = false
        // 判断是否还有数据
        // 如果有就更新下一页的数据页码
        // 如果没有就将finish设置为完成
        if (results.length) {
          this.offset = data.data.last_id
        } else {
          this.finished = true
        }
      } catch (err) {
        // console.log('请求数据失败', err)
        this.error = true
        this.loading = false
      }
    },
  },
}
</script>
<style lang='less' scoped>
</style>
